package gu.sql2java.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

import gu.sql2java.BaseColumnCodec;
import gu.sql2java.exception.ResultSetCodecException;
import gu.sql2java.exception.UnsupportTypeException;
import static com.alibaba.fastjson.serializer.SerializerFeature.WriteDateUseDateFormat;
import static com.alibaba.fastjson.serializer.SerializerFeature.WriteNonStringKeyAsString;

import java.lang.reflect.Type;

/**
 * 基于fastjson的JSON/String字段编解码实现
 * @author guyadong
 * @since 3.21.0
 */
public class JsonColumnCodec extends BaseColumnCodec {

	@Override
	protected <T> T doDeserialize(Object columnValue, Class<T> targetType) throws ResultSetCodecException {
		return doDeserialize(columnValue,(Type)targetType);
	}
	protected <T> T doDeserialize(Object columnValue, Type targetType) throws ResultSetCodecException {
		if(columnValue instanceof String) {
			try {
				return JSON.parseObject((String)columnValue,targetType);
			} catch (JSONException e) {
				throw new ResultSetCodecException(e);
			}
		}
		if(columnValue instanceof byte[]) {
			try {
				return JSON.parseObject((byte[])columnValue,targetType);
			} catch (JSONException e) {
				throw new ResultSetCodecException(e);
			}
		}
		throw new UnsupportTypeException("UNSUPPORTED type of columnValue " + columnValue.getClass().getName());
	}

	@SuppressWarnings("unchecked")
	@Override
	protected <T> T doSerialize(Object obj, Class<T> targetType) throws ResultSetCodecException {
		if(String.class.equals(targetType)) {
			try {
				return (T) JSON.toJSONString(obj, WriteDateUseDateFormat,WriteNonStringKeyAsString);
			} catch (JSONException e) {
				throw new ResultSetCodecException(e);
			}
		}
		if (byte[].class.equals(targetType)) {
			try {
				return (T) JSON.toJSONBytes(obj, WriteDateUseDateFormat,WriteNonStringKeyAsString);
			} catch (JSONException e) {
				throw new ResultSetCodecException(e);
			}
		}
		throw new UnsupportTypeException("UNSUPPORTED type of targetType " + targetType.getName());
	}

}
